package cn.szzsi.interceptor;

/**
 * Created by haotian on 2016/12/8.
 */

import cn.szzsi._Config;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.kit.IdGen;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.SiteConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class WechatLoginInterceptor_bak implements Interceptor {
    private String appid;//微信应用id
    private String secret;//微信应用秘钥
    private static final String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    public void intercept(Invocation ai) {
        Controller c = ai.getController();
        if(isNeedWechatLogin(c,null)){
            if (!weixinLogin(c, null)) {
                //获取code并且未登录成功时,中断当前操作流程
                return;
            }
        }
        ai.invoke();
    }

    /**
     * 是否需要微信登录的判断条件：
     * 1、微信浏览器
     * 2、用户session不存在
     * 3、系统配置中开启微信登录授权
     * @param c
     * @param siteConfig
     * @return
     */
    public boolean isNeedWechatLogin(Controller c, SiteConfig siteConfig){
        boolean flag = false;
        if(CommonUtil.isWeixinBrowser(c)){//是否微信浏览器
            c.setAttr(CommonUtil.BROWSER_TYPE,"weixinBrowser");
            String loginMemberId = c.getSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME);//获取当前登录用户
            if(StrKit.isBlank(loginMemberId)){
                //int openWeixnLogin=siteConfig.getInt("openWeixnLogin");
                //if (openWeixnLogin==1) {
                    flag = true;
                //}
            }
        }
        return flag;
    }

    /**
     * 微信登录
     * 1，获取code之前
     * 2，获取code之后
     * @param c
     * @param siteConfig
     * @return
     */
    private boolean weixinLogin(Controller c, SiteConfig siteConfig){
        boolean flag = false;
        String code =c.getPara("code");
        Cookie loginMemberUsernameCookie;
        //int openWeixnLogin=siteConfig.getInt("openWeixnLogin");
        //if (openWeixnLogin==1) {//开启微信授权登录
            appid= _Config.p.get("wechat_appid");
            secret=_Config.p.get("wechat_secret");
            if(StrKit.isBlank(code)){//code为null
                String redirect_uri= "";
                String fansIndexUrl= CommonUtil.getBackUrl(c);
                try {
                    redirect_uri = URLEncoder.encode(fansIndexUrl,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String authUrl=AUTHORIZE_URL+"?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                c.redirect(authUrl);
            }else{
                //已经获取到code,根据code取access_token
                String reqUrl=ACCESS_TOKEN_URL+"?APPID="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
                String result= HttpKit.get(reqUrl);
                //System.out.println("result--------------"+result);
                JSONObject obj = JSON.parseObject(result);
                String access_token=obj.getString("access_token");
                if(StrKit.notBlank(access_token)){
                    String openid = obj.getString("openid");
                    Member member = Member.dao.isExistByOpenid(openid);
                    if (member != null) {//用户名已存在,将用户的id存入session,并且存入cookie
                        c.setAttr("loginMember", member);
                        // 写入会员登录Session
                        c.setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getStr("id"));
                        // 写入会员登录Cookie
                        loginMemberUsernameCookie = null;
                        Cookie loginTypeCookie = null;
                        try {
                            loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(member.getStr("username").toLowerCase(), "UTF-8"));
                            loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        loginMemberUsernameCookie.setPath(c.getRequest().getContextPath() + "/");
                        loginTypeCookie.setPath(c.getRequest().getContextPath() + "/");
                        c.getResponse().addCookie(loginMemberUsernameCookie);
                        c.getResponse().addCookie(loginTypeCookie);
                    } else {//用户名未存在
                        //拉取用户信息
                        String getUserInfo = USER_INFO_URL+"?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
                        String resultUserInfo = HttpKit.get(getUserInfo);
                        JSONObject userJson = JSON.parseObject(resultUserInfo);
                        String nickname = userJson.getString("nickname");
                        String sex = userJson.getString("sex");
                        String country = userJson.getString("country");
                        String province = userJson.getString("province");
                        String city = userJson.getString("city");
                        String headimgurl = userJson.getString("headimgurl");
                        String privilege = userJson.getString("privilege");
                        //String unionid=userJson.get("unionid");//待处理
                        String registerIp = c.getRequest().getRemoteAddr();
                        //保存用户信息
                        Member.saveMemberInfo("0", "0", openid, nickname, sex, country, province, city, headimgurl, privilege, null, CommonUtil.PLATFROM_FLAG, registerIp, IdGen.get().nextId(10));

                        Member saveMember = Member.dao.getByOpenid(openid);//上一步保存的信息会员
                        c.setAttr("loginMember", saveMember);
                        // 写入会员登录Session
                        c.setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, saveMember.getId());
                        // 写入会员登录Cookie
                        loginMemberUsernameCookie = null;
                        Cookie loginTypeCookie = null;
                        try {
                            loginMemberUsernameCookie = new Cookie(Member.LOGIN_MEMBER_USERNAME_COOKIE_NAME, URLEncoder.encode(saveMember.getStr("username").toLowerCase(), "UTF-8"));
                            loginTypeCookie = new Cookie(Member.LOGIN_TYPE_COOKIE_NAME, "customer");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        loginMemberUsernameCookie.setPath(c.getRequest().getContextPath() + "/");
                        loginTypeCookie.setPath(c.getRequest().getContextPath() + "/");
                        c.getResponse().addCookie(loginMemberUsernameCookie);
                        c.getResponse().addCookie(loginTypeCookie);
                    }
                    flag = true;
                }else{
                    System.out.println("我是404----------------");
                    c.render("/html/404.html");
                }
            }
        //}
        return flag;
    }
}
